<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\AliyunUtil;
use App\Helpers\ConfigUtil;
use App\Helpers\DateUtil;
use App\Helpers\Helper;
use App\Helpers\RongCloud;
use App\Model\Service\CacheService;
use App\Model\Setting\SettingUserLevel;
use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Utils\Collection;
use Hyperf\Utils\HigherOrderTapProxy;
use App\Model\Setting\SettingAppHidden;

/**
 * 用户资料表
 */
class UserProfile extends Model
{
    /**
     * 用户资料表
     */
    protected $table = 'user_profile';
    protected $fillable = [
        'user_id', 'is_official', 'nick_name', 'user_profile_id', 'city', 'gender', 'birthday', 'role', 'role_level', 'avatar', 'is_recommend', 'invite_code', 'poster', 'host_time', 'avatar_vrfy', 'longlat', 'locate_city', 'video_coin_setting', 'coin_setting', 'chat_coin_setting','qrcode','cpa_code','is_lock'
    ];

    //身份 - 普通用户
    const ROLE_USER = 1;
    //身份 - 声优
    const ROLE_HOST = 2;

    //主播级别
    const HOST_CATE_NULL = 0;
    const HOST_CATE_A = 1;
    const HOST_CATE_B = 2;
    const HOST_CATE_C = 3;
    const HOST_CATE_D = 4;
    const HOST_CATE_OFFICIAL = 10;

    //推荐
    const REC_HIGH = 1;
    const REC_NORMAL = 0;
    const REC_LOW = -1;

    //主播标签
    const HOST_MARK_NORMAL = 1; //普通
    const HOST_MARK_OFFICIAL = 2; //内部扶持

    //技能配置
    const SKILL = [1 => '游戏达人', '恋爱达人', '唱歌达人'];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    static function getUserIdByProfileId($profileId = 0)
    {
        $item = self::where(['user_profile_id' => $profileId])->first();
        return $item ? $item->user_id : 0;
    }

    /**
     * 创建记录
     */
    static function updateInfo($userId = 0, $info = [])
    {
        if (!$userId) return false;
        return self::where('user_id', $userId)->update($info);
    }

    /**
     * 更新定位
     */
    static function updateLocation($userId = 0, $longlat = '', $locateCity = '')
    {
        if (!$userId || (!$longlat && !$locateCity)) return false;
        $info = [];
        $longlat && $info['longlat'] = $longlat;
        $locateCity && $info['locate_city'] = $locateCity;
        return self::where('user_id', $userId)->update($info);
    }

    /**
     * 批量获取用户资料
     */
    static function getUsersProfile($userIds = [], $userIdKey = false, $byOrder = false)
    {
        if (empty($userIds)) return [];
        if ($byOrder) {
            $orderField = "FIELD(user_id, " . implode(",", $userIds) . ")";
            $data = self::whereIn('user_id', $userIds)->orderByRaw($orderField)->limit(1000)->get()->toArray();
        } else {
            $data = self::whereIn('user_id', $userIds)->limit(1000)->get()->toArray();
        }

        if ($userIdKey) {
            $ret = [];
            foreach ($data as $item) $ret[$item['user_id']] = $item;
            return $ret;
        }
        return $data;
    }

    /**
     *  获取用户信息
     */
    static function getProfile($userId = 0, $buildAvatar = true, $showLocateCity = true)
    {
        if (!$userId) return null;
        $profile = self::where('user_id', $userId)->first();
        if (!$profile) return null;
        $buildAvatar && $profile->avatar = self::buildAvatar($profile->avatar);
        $profile->age = DateUtil::dateDiff($profile->birthday, date('Y-m-d'), 'Y');
        $profile->age = $profile->age >= 18 ? $profile->age : 18;
        $showLocateCity && $profile->locate_city && $profile->city = $profile->locate_city;
        return $profile;
    }

    /**
     * 用户性别
     */
    static function getGender($userId = 0)
    {
        if (!$userId) return -1;
        $profile = self::where('user_id', $userId)->first();
        return !$profile ? -1 : $profile->gender;
    }

    /**
     * 批量获取用户资料
     */
    static function getInfoByProfileId($profileUserId = 0)
    {
        if (!$profileUserId) return null;
        $profile = self::where('user_profile_id', $profileUserId)->first();
        if (!$profile) return null;
        $profile->avatar = AliyunUtil::IMG_HOST . $profile->avatar;
        $profile->age = DateUtil::dateDiff($profile->birthday, date('Y-m-d'), 'Y');
        return $profile;
    }

    /**
     * 构造用户账号ID
     */
    static function makeProfileUid($userId = 0)
    {
        $item = self::where('user_id', $userId)->first();
        if ($item && $item->user_profile_id) return $item->user_profile_id;
        $goodNums = [3901314];
        $uid = 3900000 + $userId;
        foreach ($goodNums as $goodNum) {
//            if ($uid == $goodNum) $uid++;
            while (self::where('user_profile_id', $uid)->count() > 0) {
                $uid++;
            }
        }
        return $uid;
    }

    /**
     * 声优列表元素结构
     */
    static function buildHostItem($userProfile = [], $imAccounts = [])
    {
        if (!$userProfile) return [];
        $voiceInfo = !$userProfile['voice'] ? null : json_decode($userProfile['voice'], true);
        $userId = $userProfile['user_id'];
        if (!$imAccounts) $imAccounts = User::getImAccounts($userId);
        $age = DateUtil::dateDiff($userProfile['birthday'], date('Y-m-d'), 'Y');
        return [
            'user_id' => $userProfile['user_id'],
            'avatar' => self::buildAvatar($userProfile['avatar']),
            'avatar_name' => $userProfile['avatar'],
            'im_account' => $imAccounts[$userId] ?? '',
            'nick_name' => $userProfile['nick_name'],
            'gender' => $userProfile['gender'],
            'online_status' => self::getOnlineStatusV2($userProfile['online'], (string)$userProfile['updated_at'], $userProfile['gender']),
            'voice' => !$voiceInfo || !isset($voiceInfo['link']) ? null : [
                'link' => AliyunUtil::VOICE_HOST . $voiceInfo['link'],
                'duration' => $voiceInfo['duration'],
            ],
            'age' => $age >= 18 ? $age : 18,
            'level' => SettingUserLevel::getUserLevel($userProfile),
            'coin_setting' => $userProfile['coin_setting'],
            'video_coin_setting' => $userProfile['video_coin_setting'],
            'chat_coin_setting' => $userProfile['chat_coin_setting'],
            //身份
            'role' => $userProfile['role'],
//            'city' => $userProfile['city'],
            'city' => '',
            //真人头像认证
            'real_avatar' => $userProfile['avatar'] && $userProfile['avatar_vrfy'] ? 1 : 0,
            //个性签名
            'self_intro' => $userProfile['self_intro'],
            //实名
            'real_name' => UserProfile::checkRoleHost($userProfile['role']) ? 1 : 0
        ];
    }

    /**
     * 构造头像
     */
    static function buildAvatar($avatar = '', $avatarSize = 500)
    {
        if (!$avatar) return '';
        if (strpos($avatar, 'image/resize') !== false) return $avatar;
        $avatar = strpos($avatar, 'http') !== false ? $avatar : AliyunUtil::IMG_HOST . $avatar;
        return AliyunUtil::imageResize($avatar, $avatarSize, $avatarSize);
    }

    /**
     * 构造头像
     */
    static function buildAvatarHW($avatar = '', $width = 100, $height = 100)
    {
        if (strpos($avatar, 'image/resize') !== false) return $avatar;
        $avatar = strpos($avatar, 'http') !== false ? $avatar : AliyunUtil::IMG_HOST . $avatar;
        return AliyunUtil::imageResize($avatar, $width, $height);
    }

    /**
     * 构造头像
     */
    static function buildAvatarArtwork($avatar = '')
    {
        if (!$avatar) return '';
        if (strpos($avatar, 'image/resize') !== false) return $avatar;
        $avatar = strpos($avatar, 'http') !== false ? $avatar : AliyunUtil::IMG_HOST . $avatar;
        return $avatar;
    }

    /**
     * 用户列表元素结构
     */
    static function buildUserItem($userProfile = [], $imAccounts = [], $avatarSize = 100,$avatarFlag=false)
    {
        $voiceInfo = !$userProfile['voice'] ? null : json_decode($userProfile['voice'], true);
        $userId = $userProfile['user_id'];
        if (!$imAccounts) $imAccounts = User::getImAccounts($userId);
        return [
            'user_id' => $userId,
            'avatar' => $avatarFlag == true ? self::buildAvatarArtwork($userProfile['avatar']) : self::buildAvatar($userProfile['avatar'], $avatarSize),
            'im_account' => $imAccounts[$userId] ?? '',
            'nick_name' => $userProfile['nick_name'],
            'gender' => $userProfile['gender'],
            'online_status' => $userProfile['online'], //self::getOnlineStatus($userProfile['online'], $userProfile['updated_at']),
            'voice' => (!$voiceInfo || !isset($voiceInfo['link'])) ? null : [
                'link' => AliyunUtil::VOICE_HOST . $voiceInfo['link'],
                'duration' => $voiceInfo['duration'],
            ],
            'age' => DateUtil::dateDiff($userProfile['birthday'], date('Y-m-d'), 'Y'),
            'self_intro' => $userProfile['self_intro'],
            'city' => $userProfile['city'],
            'rich_value' => $userProfile['rich_value'],
            'level' => SettingUserLevel::getUserLevel($userProfile),
            //身份
            'role' => $userProfile['role'],
            //真人头像认证
            'real_avatar' => $userProfile['avatar'] && $userProfile['avatar_vrfy'] ? 1 : 0,
            //个性签名
            'self_intro' => $userProfile['self_intro'],
        ];
    }

    /**
     * 推荐用户
     */
    static function buildRecItem($userProfile = [], $imAccounts = [], $avatarSize = 100)
    {
        $userId = $userProfile['user_id'];
        if (!$imAccounts) $imAccounts = User::getImAccounts($userId);
        return [
            'user_id' => $userId,
            'avatar' => self::buildAvatar($userProfile['avatar'], $avatarSize),
            // 'im_account' => $imAccounts[$userId] ?? '',
            'nick_name' => $userProfile['nick_name'],
            'gender' => $userProfile['gender'],
            'online_status' => self::getOnlineStatus($userProfile['online'], $userProfile['updated_at']),
        ];
    }

    /**
     * 用户详情结构
     */
    static function buildProfileDetail($userProfile = null, $showLocateCity = true)
    {
        if (!$userProfile) return [];
        if (!is_array($userProfile)) $userProfile = $userProfile->toArray();
        $info = self::buildHostItem($userProfile);
        //个人展示图
        $bigPosters = $posters = !$userProfile['poster'] ? [] : explode(',', trim($userProfile['poster'], ','));
        foreach ($bigPosters as &$poster) {
            $poster = AliyunUtil::imageResize(AliyunUtil::IMG_HOST . $poster);
        }
        return array_merge($info, [
            'user_profile_id' => $userProfile['user_profile_id'],
            'birthday' => $userProfile['birthday'],
            'rich_value' => (string)$userProfile['rich_value'],
            'charm_value' => (string)$userProfile['charm_value'],
            'city' => $showLocateCity && $userProfile['locate_city'] ? $userProfile['locate_city'] : $userProfile['city'],
            'self_intro' => $userProfile['self_intro'],
            'skills' => self::buildSkills($userProfile['skills']),
            'big_poster' => $bigPosters ?: [$info['avatar']],
            'poster_name' => $posters,
            //是否展示星标
            'star_mark' => $userProfile['role'] == self::ROLE_HOST ? 1 : 0,
        ]);
    }

    /**
     * 技能数组
     */
    static function buildSkills($skills = '')
    {
        if (!$skills) return [];
        $skills = explode(',', $skills);
        $colors = ['#FFE0DF', '#FFF2E0', '#E5F0FE', '#E9E5FE'];
        $data = [];
        array_walk($skills, function ($skill, $k) use ($colors, &$data) {
            $data[] = ['bg_color' => $colors[$k % 4], 'skill' => $skill, 'selected' => 1];
        });
        return $data;
    }

    /**
     * 获取推荐的用户
     */
    static function getRecUsers($role = self::ROLE_USER, $gender = -1)
    {
        return Db::table('user_profile')->join('user', function ($join) use ($role, $gender) {
            $where = [
                ['status', '=', User::STATUS_OK],
                // ['is_official', 0],
                // ['user_profile.is_recommend', '=', self::REC_HIGH],
            ];
            if ($role) {
                $where[] = ['user_profile.role', '=', $role];
            }
            if ($gender > -1) {
                $where[] = ['user_profile.gender', '=', $gender];
            }
            $join->on('user.id', '=', 'user_profile.user_id')
                ->where($where);
        })->pluck('user_id')->toArray();
    }

    /**
     * 获取最新的用户
     */
//    static function getNewUsers($role = self::ROLE_USER, $gender = -1, $limit = 500, $showRec = false)
//    {
//        return Db::table('user_profile')->join('user', function ($join) use ($role, $gender, $showRec) {
//            $where = [
//                ['status', '=', User::STATUS_OK],
//                // ['is_official', 0],
//                // ['avatar', '<>', 'default/fe_avatar.jpeg'],
//                ['is_recommend', '<>', self::REC_LOW]
//            ];
//            if ($role) $where[] = ['user_profile.role', '=', $role];
//            if ($gender > -1) $where[] = ['user_profile.gender', '=', $gender];
//            $join->on('user.id', '=', 'user_profile.user_id')->where($where);
//        })->orderBy('online', 'desc')->orderBy('user_id', 'desc')->limit($limit)->pluck('user_id')->toArray();
//    }

    /**
     * @Cacheable(prefix="user_profile_online", ttl=30, value="_#{online}", listener="user_profile_online")
     * 在线推荐的主播
     */
    static function getOnlineRecHosts($online = -1)
    {
        $hostIds = Db::table('user_profile')->join('user', function ($join) use ($online) {
            $where = [
                ['status', '=', User::STATUS_OK],
                ['avatar', '<>', 'default/fe_avatar.jpeg'],
                ['gender', 0],
                ['user_id', '<>', env('KEFU_UID2', 11)],
                ['user_profile.role', '=', self::ROLE_HOST],
            ];
            if ($online == 1) $where[] = ['online', 1];
            elseif ($online == 0) $where[] = ['online', 0];
            $join->on('user.id', '=', 'user_profile.user_id')->where($where);
        })->limit(500)->pluck('user_id')->toArray();
        //黑名单的主播
        $blackHosts = CacheService::blackHosts();
        return array_diff($hostIds, $blackHosts);
    }

    /**
     * 获取推荐接听的声优
     */
    static function getRecHosts($gender = -1, $online = -1, $callType = VoiceCall::CALL_TYPE)
    {
        return Db::table('user_profile')->join('user', function ($join) use ($gender, $online, $callType) {
            $where = [
                ['status', '=', User::STATUS_OK],
                ['is_official', 0],
                ['user_profile.role', '=', self::ROLE_HOST],
            ];
            if ($callType == VoiceCall::CALL_TYPE) $where[] = ['call_permit', 1];
            elseif ($callType == VideoCall::CALL_TYPE) $where[] = ['video_permit', 1];
            if ($online > -1) $where[] = ['online', $online];
            if ($gender > -1) $where[] = ['user_profile.gender', '=', $gender];
            $join->on('user.id', '=', 'user_profile.user_id')->where($where);
        })->orderBy('online', 'desc')->pluck('user_id')->toArray();
    }

    /**
     * 修改语音接听允许状态
     */
    static function updateCallPermit($userId = 0, $permit = 1)
    {
        return self::where('user_id', $userId)->limit(1)->update(['call_permit' => $permit]);
    }

    /**
     * 修改视频通话允许状态
     */
    static function updateVideoPermit($userId = 0, $permit = 1)
    {
        return self::where('user_id', $userId)->limit(1)->update(['video_permit' => $permit]);
    }

    /**
     * 获取剩余免费通话时长
     */
    static function getFreeCallTime($userId)
    {
        $item = self::where('user_id', $userId)->first();
        return $item ? $item->free_call_time : 0;
    }

    /**
     * 查找昵称
     */
    static function searchByNick($keyword = '')
    {
        $where = [
            ['nick_name', 'like', "%{$keyword}%"],
        ];
        return self::where($where)->get()->toArray();
    }

    /**
     * 获取一批模糊头像
     */
    static function getBlurAvatars($num, $size = 100)
    {
        $where = [
            ['gender', 0],
            ['role', self::ROLE_HOST],
            ['avatar', '<>', '']
        ];
        $avatars = self::where($where)->limit($num)->pluck('avatar')->toArray();
        foreach ($avatars as &$avatar) {
            $avatar = AliyunUtil::blurImage($avatar, $size, $size);
        }
        return $avatars;
    }

    /**
     * 获取邀请人ID
     */
    static function getInviteCode($userId = 0)
    {
        $profile = self::getProfile($userId);
        return $profile ? intval($profile->invite_code) : 0;
    }

    /**
     * 是否能发起语聊
     */
    static function checkCanCall($role = self::ROLE_USER, $permit = 1)
    {
        return $role == self::ROLE_HOST  ? 1 : 0; //&& $permit == 1
    }

    /**
     * 是否能发起视频聊天
     */
    static function checkCanVideo($role = self::ROLE_USER, $permit = 1)
    {
        return $role == self::ROLE_HOST  ? 1 : 0; //&& $permit == 1
    }

    /**
     * 增加免费语聊时长（分钟）
     */
    static function addFreeCallTime($userId = 0, $freeCallTime = 0)
    {
        return self::where('user_id', $userId)->increment('free_call_time', $freeCallTime);
    }

    /**
     * 减少免费语聊时长（分钟）
     */
    static function delFreeCallTime($userId = 0, $decFreeCallTime = 0)
    {
        $profile = self::getProfile($userId);
        if ($profile->free_call_time <= $decFreeCallTime) {
            return self::where('user_id', $userId)->update(['free_call_time' => 0]);
        }
        return self::where('user_id', $userId)->decrement('free_call_time', $decFreeCallTime);
    }

    /**
     * 推荐用户或声优
     */
    static function getRecProfiles($host = false)
    {
        $where = [
            ['gender', 0],
            ['poster', '<>', ''],
            ['is_official', 0]
        ];
        $orWhere = [
            ['gender', 0],
            ['voice', '<>', ''],
            ['is_official', 0]
        ];
        if ($host) $where[] = $orWhere[] = ['role', self::ROLE_HOST];
        else $where[] = $orWhere[] = ['role', '<>', self::ROLE_HOST];
        return self::where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->select(['user_id', 'poster', 'voice', 'online'])->get()->toArray();
    }

    /**
     * 最近注册用户
     */
    static function getRecentRegister($days = 7, $host = false)
    {
        $where = [
            ['created_at', '>', date('Y-m-d', strtotime("-{$days} day"))],
            ['is_official', 0]
        ];
        if ($host) $where[] = $orWhere[] = ['role', self::ROLE_HOST];
        return self::where($where)->pluck('user_id')->toArray();
    }

    /**
     * 检测用户是否声优角色
     */
    static function checkIsHost($hostId = 0, $userProfile = null)
    {
        if (!$userProfile) $userProfile = self::getProfile($hostId);
        return $userProfile && $userProfile->role == self::ROLE_HOST ? 1 : 0;
    }

    /**
     * 获取邀请人数
     */
    static function getInviteCount($profileId = '')
    {
        return self::where('invite_code', $profileId)->count();
    }

    /**
     * 获取邀请的用户ID
     */
    static function getInviteUsers($profileId = '')
    {
        if ($profileId) {
            return self::where('invite_code', $profileId)->pluck('user_id')->toArray();
        }
        return [];
    }

    /**
     * 获取当前用户在线状态
     */
    static function getOnlineStatus($online = 0, $onlineTime = '')
    {
        if ($online == 1) return 1;
        // if ($onlineTime && strtotime((string)$onlineTime) > (time() - 3600)) return 1;
        return 0;
    }

    /**
     * 获取当前用户在线状态（分男女用户）
     */
    static function getOnlineStatusV2($online = 0, $onlineTime = '', $gender = 1)
    {
        if ($online == 1) {
            return 1;
        }

         if ($onlineTime && strtotime((string)$onlineTime) > (time() - 1800) && $gender == 1) {
             return 1;
         }

        return 0;
    }

    /**
     * 判断用户免费通话的有效时间是否过期
     */
    static function checkFreeTimeExpired($startTime = '')
    {
        $expDays = ConfigUtil::getBusiConfig('new_free_expire');
        return strtotime("-{$expDays} day") > strtotime($startTime);
    }

    /**
     * 是否普通用户
     */
    static function checkRoleUser($role)
    {
        return $role == self::ROLE_USER;
    }

    /**
     * 是否声优角色
     */
    static function checkRoleHost($role)
    {
        return $role == self::ROLE_HOST;
    }

    /**
     * 更新自动回复信息
     */
    static function updateAutoMsg($userId = 0, $text = '', $voice = '', $duration = 0)
    {
        $info = [];
        $text && $info['auto_msg_text'] = $text;
        $voice && $info['auto_msg_voice'] = $voice;
        $duration && $info['auto_voice_duration'] = $duration;
        if (!$info) return 0;
        return self::where(['user_id'  => $userId])->limit(1)->update($info);
    }

    /**
     * 清除自动消息回复
     */
    static function delAutoMsg($userId = 0, $type = 'text')
    {
        if ($type == 'voice') $info = ['auto_msg_voice' => ''];
        else $info = ['auto_msg_text' => ''];
        return self::where(['user_id'  => $userId])->limit(1)->update($info);
    }

    /**
     * 获取当前在线的用户ID
     */
    static function getOnlineUsers($role = 0, $num = 20, $gender = -1)
    {
        $where = [
            ['online', 1],
            ['avatar', '<>', 'default/fe_avatar.jpeg']
        ];
        if ($role > 0) $where[] = ['role', $role];
        if ($gender > -1) $where[] = ['gender', $gender];
        // if ($callPermit) {
        //     $where[] = ['call_permit', 1];
        //     $where[] = ['video_permit', 1];
        // }
        return self::where($where)->orderBy('user_id', 'desc')->limit($num)->pluck('user_id')->toArray();
    }

    /**
     * 更新融云信息
     */
    static function updateRongCloudInfo($imAccount = '', $name = '', $avatar = '')
    {
        return (new RongCloud())->userRefresh($imAccount, $name, $avatar);
    }

    /**
     * 获取推荐接听的声优
     */
    static function getOldIds($appVersion = '1.0.1', $role = self::ROLE_HOST)
    {
        return Db::table('user_profile')->join('user', function ($join) use ($role, $appVersion) {
            $where = [
                ['user_profile.role', '=', $role],
                ['version', '<', $appVersion],
            ];
            $join->on('user.id', '=', 'user_profile.user_id')->where($where);
        })->pluck('user_id')->toArray();
    }

    /**
     * 注册用户
     */
    static function getRegCount($gender = -1, $role = -1, $startTime = '', $endTime = '', $channel = '', $datatype = 'count', $avatarVery = -1)
    {
        $where = [];
        if ($startTime) $where[] = ['user_profile.created_at', '>=', $startTime];
        if ($endTime) $where[] = ['user_profile.created_at', '<', $endTime];
        if ($gender > -1) $where[] = ['gender', '=', $gender];
        if ($role > -1) $where[] = ['role', '=', $role];
        if ($avatarVery > -1) {
            $where[] = ['avatar_vrfy', '=', $avatarVery];
        }
        //指定渠道
        if (!$channel) {
            $query = self::where($where);
        } else {
            $query = Db::table('user_profile')->join('user', function ($join) use ($where, $channel) {
                $where[] = ['channel', $channel];
                $join->on('user.id', '=', 'user_profile.user_id')->where($where);
            });
        }
        return $datatype != 'count' ? $query->pluck('user_id')->toArray() : $query->count();
    }

    /**
     * 是否有效的ID
     */
    static function isProfileIdValid($profileId = '')
    {
        if (!Helper::isProfileIdValid($profileId)) return false;
        return self::where('user_profile_id', $profileId)->count() ? true : false;
    }

    /**
     * 选择昵称
     */
    static function pickAvatar($gender = 0)
    {
        // return $gender == 0 ? 'default/fe_avatar.jpeg' : 'default/ma_avatar.jpeg';
        if ($gender == 0) return 'default/fe_avatar.jpeg';
        $avatarIdx = rand(1, 51);
        return "default/a-{$avatarIdx}.jpg";
    }

    /**
     * 查询性别
     */
    static function checkGender($userId = 0, $genderType = 'male', $profile = null)
    {
        if (!$profile) $profile = self::getProfile($userId);
        return ($genderType == 'male' && $profile->gender == 1) || ($genderType == 'female' && $profile->gender == 0);
    }

    /**
     * 头像是否真人认证
     */
    static function checkAvatarVrfied($userId = 0, $profile = null)
    {
        if (!$profile) $profile = self::getProfile($userId);
        return $profile->avatar && $profile->avatar_vrfy ? 1 : 0;
    }

    /**
     * 照片墙（视频+照片）
     */
    static function getPosters($userId = 0, $profile = null, $resize = true)
    {
        if (!$profile) $profile = self::getProfile($userId);
        $posters = !$profile->poster ? [] : explode(',', $profile->poster);
        $video = $profile->video ? json_decode($profile->video, true) : [];
        foreach ($posters as &$poster) {
            $poster = $resize
                ? AliyunUtil::imageResize(AliyunUtil::IMG_HOST . $poster)
                : AliyunUtil::IMG_HOST . $poster;
        }
        return [
            'video' => $video ? AliyunUtil::VOICE_HOST . $video['link'] : '',
            'photo' => $posters
        ];
    }

    /**
     * 资料完善
     */
    static function checkProfileComplete($profile = null)
    {
        if (!$profile) return 0;
        $checkFields = ['poster', 'self_intro', 'voice', 'video'];
        foreach ($checkFields as $field) if (!$profile->{$field}) return 0;
        return 1;
    }

    /**
     * 多个用户资料（object）
     */
    static function getUsersProfileObj($userIds = [])
    {
        $data = self::whereIn('user_id', $userIds)->limit(1000)->get();
        $ret = [];
        foreach ($data as $item) {
            $item->avatar = self::buildAvatar($item->avatar);
            $item->age = DateUtil::dateDiff($item->birthday, date('Y-m-d'), 'Y');
            $item->age = $item->age >= 18 ? $item->age : 18;
            $ret[$item['user_id']] = $item;
        }
        return $ret;
    }

    /**
     * 获取体力值
     */
    static function getEnergy($userId = 0)
    {
        $userCoin = UserCoin::getUserInfo($userId);
        return $userCoin ? "{$userCoin['real_total_coin']}" : "";
    }

    /**
     * 获取最新的用户
     * @param int $role
     * @param int $gender
     * @param int $online
     * @return array
     */
    public function getNewUsersV2(int $role = self::ROLE_USER, int $gender = -1, int $online = 1): array
    {
        $where = [
            ['is_recommend', '<>', self::REC_LOW],
            ['online', '=', $online]
        ];

        if ($role) {
            $where[] = ['role', '=', $role];
        }

        if ($gender > -1) {
            $where[] = ['gender', '=', $gender];
        }

        $result = Db::table('user_profile')->join('user', 'user.id', '=', 'user_profile.user_id')
            ->where($where)
            ->where('user.status', User::STATUS_OK)
            ->pluck('user_id')
            ->toArray();

        $hiddenData = empty($limitHiddenCity = config('busi.limit_hidden_city_string')) ? [] :
            Db::table('user_profile')
                ->whereIn('locate_city', explode(',', $limitHiddenCity))
                ->pluck('user_id')
                ->toArray();

        return array_diff($result, $hiddenData);
    }

    /**
     * @Cacheable(prefix="get_freeze_users_v", ttl=20, listener="get_freeze_users_v")
     * @return array
     */
    public function getFreezeStatusUsers()
    {
        $userIds = Db::table('user')
            ->whereIn('status',[User::STATUS_FREEZE,User::STATUS_CANCELLATTED,User::STATUS_FORBID])
            ->pluck('id');

        if (empty($userIds))
        {
            return [];
        }

        return $userIds->toArray();
    }

    /**
     * @Cacheable(prefix="get_new_users_v", ttl=20, value="_#{role}", listener="get_new_users_v")
     * 获取最新的用户
     */
    static function getNewUsers($role = self::ROLE_USER, $gender = -1, $limit = 500,$notuid=[])
    {
        //屏蔽用户
        $hiddenWhere = SettingAppHidden::getHiddenWhere();
        $userIds = Db::table('user_profile')->join('user','user.id','=','user_profile.user_id')
            ->where(function($query) use ($role, $gender,$notuid,$hiddenWhere){
                $where = [
                    ['status', '=', User::STATUS_OK],
                    ['is_recommend', '<>', self::REC_LOW]
                ];
                if ($role) $where[] = ['user_profile.role', '=', $role];
                if ($gender > -1) $where[] = ['user_profile.gender', '=', $gender];
                //屏蔽特定地区
                $limitHiddenCity = config('busi.limit_hidden_city_string');
                $limitHiddenCity = empty($limitHiddenCity) ? [] : explode(',',$limitHiddenCity);
                if($limitHiddenCity){
                    $query->where($where)->whereNotIn('user_profile.locate_city',$limitHiddenCity);
                }else{
                    $query->where($where);
                }
                if($notuid) $query->whereNotIn('user.id',$notuid);
//                if($gender != 0){
//                    if($hiddenWhere) $query->whereRaw($hiddenWhere);
//                }
            });

//        if ($gender != 0) {
//            $userIds = (new SettingAppHidden())->getAppHiddenSubQuery($userIds);
//        }

        $userIds = $userIds->orderBy('online', 'desc')
            ->orderBy('user_id', 'desc')->limit($limit)
            ->pluck('user_id')->toArray();

        if ($gender != 0) {
            $excludeUsers = SettingAppHidden::getExcludeUsers();

            $userIds = array_diff($userIds, $excludeUsers);
        }

        return $userIds;
    }

    /**
     * 获取最新的用户
     */
    static function getTagUserList($role = self::ROLE_USER, $gender = -1, $start=0,$pagnum=20,$notuid=[])
    {
        //屏蔽用户
        $hiddenWhere = SettingAppHidden::getHiddenWhere();
        $userIds = Db::table('user_profile')->join('user','user.id','=','user_profile.user_id')
            ->where(function($query) use ($role, $gender,$notuid,$hiddenWhere){
                $where = [
                    ['status', '=', User::STATUS_OK],
                    ['is_recommend', '<>', self::REC_LOW],
                    ['user.id','>',10]
                ];
                if ($role) $where[] = ['user_profile.role', '=', $role];
                if ($gender > -1) $where[] = ['user_profile.gender', '=', $gender];
                //屏蔽特定地区
                $limitHiddenCity = config('busi.limit_hidden_city_string');
                $limitHiddenCity = empty($limitHiddenCity) ? [] : explode(',',$limitHiddenCity);
                if($gender == 1){
                    if($limitHiddenCity){
                        $query->where($where)->whereNotIn('user_profile.locate_city',$limitHiddenCity);
                    }else{
                        $query->where($where);
                    }
//                    if($hiddenWhere) $query->whereRaw($hiddenWhere);
                }else{
                    $query->where($where);
                }
//                $query->where($where);
                if($notuid) $query->whereNotIn('user.id',$notuid);
            });

//        if ($gender == 1) {
//            $userIds = (new SettingAppHidden())->getAppHiddenSubQuery($userIds);
//        }

        $userIds = $userIds->orderBy('online', 'desc')->orderBy('user_id', 'desc')->offset($start)->limit($pagnum)->get()->toArray();

        // 排除屏蔽的用户
        if ($gender == 1) {
            $excludeUsers = SettingAppHidden::getExcludeUsers();
            foreach ($userIds as $key => $val) {
                if (in_array($val->user_id, $excludeUsers)) {
                    unset($userIds[$key]);
                }
            }
        }

        return $userIds;
    }

    /**
     * 获取测试
     * @param $role
     * @param $gender
     * @param $start
     * @param $pagnum
     * @param $notuid
     * @return array
     */
    static function getTestUserId($role = self::ROLE_USER, $gender = -1, $start=0,$pagnum=20,$notuid=[]){
        $hiddenWhere = SettingAppHidden::getHiddenWhere();
        return Db::table('user_profile')->join('user','user.id','=','user_profile.user_id')
            ->where(function($query) use ($role, $gender,$notuid,$hiddenWhere){
                $where = [
                    ['status', '=', User::STATUS_OK],
                    ['is_recommend', '<>', self::REC_LOW],
                    ['user.id','>',10],
                    ['user.phone','like','240%']
                ];
                if ($role) $where[] = ['user_profile.role', '=', $role];
                if ($gender > -1) $where[] = ['user_profile.gender', '=', $gender];
                //屏蔽特定地区
                $limitHiddenCity = config('busi.limit_hidden_city_string');
                $limitHiddenCity = empty($limitHiddenCity) ? [] : explode(',',$limitHiddenCity);
                if($gender == 1){
                    if($limitHiddenCity){
                        $query->where($where)->whereNotIn('user_profile.locate_city',$limitHiddenCity);
                    }else{
                        $query->where($where);
                    }
                    if($hiddenWhere) $query->whereRaw($hiddenWhere);
                }else{
                    $query->where($where);
                }
//                $query->where($where);
                if($notuid) $query->whereNotIn('user.id',$notuid);
            })
            ->orderBy('online', 'desc')->orderBy('user_id', 'desc')->offset($start)->limit($pagnum)->get()->toArray();
    }

    /**
     * @Cacheable(prefix="online_list", ttl=15, listener="online_list")
     * 获取所有在线的人
     * @return array
     */
    public static function getOnlineUserAll()
    {
        return self::where([
            ['online','=',1],
            ['gender','<>',-1]
        ])->pluck('user_id')->toArray();
    }

    /**
     * 根据userId 获取role
     * @param $userId
     * @return HigherOrderTapProxy|mixed|null
     */
    static function getRoleByUserId($userId)
    {
        return self::where('user_id', $userId)->value('role');
    }

    /**
     * 根据财富值获取用户id
     * @param $value
     * @return array
     */
    static function getUserIdByRichValue($value): array
    {
        return self::where([
            ['rich_value','>=',$value],
            ['gender','=',1]
        ])->pluck('user_id')->toArray();
    }

    /**
     * 根据时间获取活跃用户
     * @param $updateTime
     * @return array
     */
    public static function getRecentlyActiveUserIdByTime($updateTime): array
    {
        return self::where([
            ['updated_at','>=',$updateTime],
            ['gender','<>',-1]
        ])->pluck('user_id')->toArray();
    }

    /**
     * 获取所有数据
     * @return array
     */
    public static function getRecentlyActiveUserIdAll(): array
    {
        return self::where([
            ['gender','<>',-1]
        ])->pluck('user_id')->toArray();
    }

    /**
     * 获取未认证女用户数据
     * @return array
     */
    public static function getNoAvatarVrfy()
    {
        return self::where([
            ['gender','=',0],
            ['avatar_vrfy','=',0]
        ])->pluck('user_id')->toArray();
    }

  /**
   * 获取状态非正常女用户
   * @return array
   */
    public static function getAbnormalUser()
    {
      return self::leftJoin('user', 'user_profile.user_id', '=', 'user.id')
      ->where([
        ['user_profile.gender','=',0],
        ['user.status','<>',0]
      ])->pluck('user_profile.user_id')->toArray();
    }
}
